package com.yzy.mall.component

import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.text.InputType
import android.text.method.NumberKeyListener
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.*
import com.decard.NDKMethod.BasicOper
import com.decard.entitys.IDCard
import com.yzy.baselibrary.extention.*
import com.yzy.baselibrary.extention.StatusBarHelper.setStatusBarLightMode
import com.yzy.mall.R
import com.yzy.mall.component.comm.CommActivity
import com.yzy.mall.repository.CardViewModel
import com.yzy.mall.repository.UpdateGlobal
import com.yzy.mall.repository.ViewModelFactory
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.item_view_layout.view.*


class MainActivity : CommActivity() {

    override fun layoutResId(): Int = R.layout.activity_main
    private val mViewModel: CardViewModel by lazy {
        ViewModelProvider(
            this,
            ViewModelFactory()
        ).get(CardViewModel::class.java)
    }

    var idCard: IDCard? = null
    var leftDrawable: Drawable? = null

    var idCardStr: String? = null
    var devHandle: Int = -1

    //获取USB权限
    override fun initView() {
        setStatusBarLightMode(this)
        leftDrawable = AppCompatResources.getDrawable(mContext, R.drawable.icon_left)
        leftDrawable?.let {
            it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight)
        }
//        tvEditView.keyListener = object : NumberKeyListener() {
//            override fun getInputType(): Int {
//                return InputType.TYPE_CLASS_PHONE
//            }
//
//            override fun getAcceptedChars(): CharArray {
//                return charArrayOf('1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'x')
//            }
//        }

//        showLoadingView()

//        Glide.with(this).load(R.drawable.bg).into(bg_view)
        tvQuerySubmit.click {
//            idCardStr = "513030198601011015"
//            mViewModel.getCard(idCardStr)
            if (devHandle ==-1){
                devHandle = BasicOper.dc_open("AUSB", this, "", 0);
            }
            KeyboardUtils.hideSoftInput(tvEditView)
//            idCardStr = "513030198704181012"
//            mViewModel.getCard(idCardStr)
            LogUtils.e("dc_open$devHandle")
            idCardStr = tvEditView.text.trim().toString()
            if (devHandle > 0) {
                idCard = BasicOper.dc_SamAReadCardInfo(1)
                LogUtils.e(idCard)
                when {
                    idCard != null -> {
                        idCardStr = idCard?.id ?: ""
                        tvEditView.setText(idCardStr)
                        checkCard(idCardStr)
                    }
                    idCardStr != null && (idCardStr?.length ?: 0) > 0 -> {
                        idCard = null
                        checkCard(idCardStr)
                    }
                    else -> {
                        toast("请将身份证放在读卡机上，或者输入身份证号!!!")
                    }
                }
            } else {
                if ((idCardStr?.length ?: 0) > 0) {
                    checkCard(idCardStr)
                } else {
                    toast("请输入身份证号!!!")
                }
            }
        }
        tvCloseSubmit.click {
            closeCloseSubmit()
        }
        UpdateGlobal.addObserve(this,{
            mViewModel.getCard(idCardStr)
        })
        tvRegisterSubmit.click {
            KeyboardUtils.hideSoftInput(tvEditView)
            val phone = tvPhone.text.trim().toString()
            if (!RegexUtils.isMobileExact(phone)) {
                toast("请输入正确手机号")
                return@click
            }
            mViewModel.wineMembers(
                edUserIdCard.text.trim().toString(),
                tvPhone.text.trim().toString(),
                edUserName.text.trim().toString(),
                idCard?.address ?: ""
            )
        }

        tvErrorCloseSubmit.click {
            closeError()
        }
        tvLeft.tag = "left"
        tvLeft.click {
            val tag = tvLeft.tag as String
            when (tag) {
                "left" -> {

                }
                "error" -> {
                    closeError()
                }
                "success" -> {
                    closeCloseSubmit()
                }
                "register" -> {
                    closeCloseSubmit()
                }
            }
        }
    }

    private fun closeCloseSubmit() {
        setLeft()
        tvUserName.gone()
        tvNumber.gone()
        tvTime.gone()
        tvTopName.gone()
        llBottomView.gone()


    }

    private fun closeError() {
        setLeft()
        tvErrorCloseSubmit.gone()
        tvErrorTime.gone()
    }

    private  fun checkCard(card:String?){
        card?.let {
            if (!RegexUtils.isIDCard18(card)){
                toast("请输入有效身份证号")
                return
            }
            mViewModel.getCard(idCardStr)
        }


    }

    private fun setLeft() {
        tvLeft.text = "查询"
        tvQuerySubmit.visible()
        tvEditView.visible()
        ivBg.gone()
        cardState.gone()
        tvLeft.tag = "left"
        tvLeft.setCompoundDrawables(null, null, null, null)
        tvLeft.compoundDrawablePadding = 0
        llRegister.gone()
        idCardStr = null
        idCard = null
        tvEditView.setText("")
    }

//    private fun selectInfo() {
//        mViewModel.getCard(idCardStr)
//    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        mViewModel.uiRegisterState.observe(this, Observer {
            val showLoading = it?.showLoading ?: false
            if (showLoading) {
                showLoadingView()
            } else {
                dismissLoadingView()
            }
            it?.success?.let { register ->
                val b = register as Boolean
                if (b) {
                    idCardStr = edUserIdCard.text.toString()
                    mViewModel.getCard(idCardStr)
                    tvPhone.setText("")
                    edUserIdCard.setText("")
                    edUserName.setText("")
                }
            }
        })
        mViewModel.uiState.observe(this, Observer {
            val showLoading = it?.showLoading ?: false
            if (showLoading) {
                showLoadingView()
            } else {
                dismissLoadingView()
            }
            it?.success?.let { list ->
                tvQuerySubmit.gone()
                tvEditView.gone()
                tvLeft.setCompoundDrawables(leftDrawable, null, null, null)
                tvLeft.compoundDrawablePadding = 30
                val member = list.memberInfo
                if (member != null ) {
                    llRegister.gone()
                    member.let { info ->
                        tvUserName.text = SpanUtils().append("用户名：").setFontSize(24, true)
                            .append(info.userName ?: "").setFontSize(30, true).create()
                        tvNumber.text = SpanUtils().append("当前剩余可够商品积分合计：").setFontSize(24, true)
                            .append(info.residualPoints.toString()).setFontSize(28, true).create()
                        tvTime.text = "当前截止时间： ${TimeUtils.millis2String(
                            System.currentTimeMillis(),
                            "yyyy-MM-dd"
                        )}"
                    }

                    tvLeft.text = "查询结果"
                    cardState.visible()
                    ivBg.visible()
                    if (list.limitedstatus == "禁止购买") {
                        cardState.text = "该用户为黑名单，不可购买积分商品"
                        tvErrorTime.text = "当前截止时间： ${TimeUtils.millis2String(
                            System.currentTimeMillis(),
                            "yyyy-MM-dd"
                        )}"
                        tvErrorTime.visible()
                        ivBg.setImageResource(R.drawable.icon_error)
                        tvErrorCloseSubmit.visible()
                        tvExchangeSubmit.gone()
                        tvLeft.tag = "error"
                    } else {
                        tvLeft.tag = "success"
                        cardState.text = "该用户为已注册用户"
                        ivBg.setImageResource(R.drawable.icon_sucess)
                        tvUserName.visible()
                        tvNumber.visible()
                        tvTime.visible()
                        tvTopName.visible()
                        llBottomView.visible()
                        tvExchangeSubmit.visible()
                        val violationRecord = list.violation_record ?: mutableListOf()
                        if (violationRecord.isNotEmpty()) {
                            tvExchangeSubmit.click {
                                ExchangeActivity.startExchangeActivity(mContext,list)
                            }
                            llListView.removeAllViews()
                            violationRecord.forEach { bean ->
                                val inflate = mContext.inflate(R.layout.item_view_layout)
                                inflate.tvName.text = bean.buy_wine_name
                                inflate.tvNumber.text = bean.single_integral.toString()
                                inflate.tvCount.text = bean.buy_number.toString()
                                llListView.addView(
                                    inflate,
                                    ViewGroup.LayoutParams(
                                        ViewGroup.LayoutParams.MATCH_PARENT,
                                        ViewGroup.LayoutParams.WRAP_CONTENT
                                    )
                                )
                            }
                        }else{
                            llListView.removeAllViews()
                            tvExchangeSubmit.gone()
                        }
                    }
                } else {
                    tvLeft.tag = "register"
                    tvLeft.text = "用户注册"
                    llRegister.visible()
                    if (idCard != null) {
                        edUserIdCard.setText(idCard?.id)
                        edUserName.setText(idCard?.name ?: "")
                    } else {
                        edUserIdCard.setText(idCardStr)
                    }
                }


            }
        })
    }

    private var touchTime = 0L
    private val waitTime = 2000L
    override fun onBackPressed() {
        val tag = tvLeft.tag as String
        if (tag != "left") {
            tvLeft.performClick()
            return
        }
        val currentTime = System.currentTimeMillis()
        if (currentTime - touchTime >= waitTime) {
            //让Toast的显示时间和等待时间相同
            toast(R.string.double_exit)
            touchTime = currentTime
        } else {
            super.onBackPressed()
        }
        return
    }
}